from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from . import web
import logging, json, random, threading

logging = logging.getLogger('django')
is_end = None
t = None

def play_game(request):
    while (not is_end):
        res = web.start(request)
        uuid = [cookie.split('=') for cookie in str(res.cookies).split(': ')[1].split('; ')][0][1]
        logging.info(uuid)
        request.COOKIES['uuid'] = uuid
        is_victory = False
        while (not is_victory):
            cell_x = random.randint(1, 15)
            cell_y = random.randint(1, 15)
            request.POST = {}
            request.POST['cellX'] = cell_x
            request.POST['cellY'] = cell_y
            resp = json.loads(web.down(request).content)
            if (resp.get('victory') != None):
                is_victory = True

@csrf_exempt
def start(request):
    global is_end
    is_end = False
    global t
    t = threading.Thread(target=play_game, args=(request,))
    t.start()
    return HttpResponse(json.dumps({'msg':'success'}), content_type='application/json')

@csrf_exempt
def end(request):
    global is_end
    is_end = True
    t.join()
    return HttpResponse(json.dumps({'msg': 'success'}), content_type='application/json')